//
//  WDProductDetailController.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/12/8.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "WDProductDetailController.h"
#import "WDProduct.h"
#import "WDProductDetail.h"
#import "WDProductBottomView.h"
#import "WDPDHeadCell.h"
#import "WDAnimateCell.h"
#import "WDFinancialDetailController.h"
#import "WDEditOrderController.h"
#import "WDCityListController.h"
#import "WDCityList.h"
#import "WDPDLeftBottom.h"
#import "WDPDBottom.h"
#import "WDPDDefaultCell.h"
#import "WDPDIntroCell.h"
#import "WDMaterialCell.h"
#import "WDPDDescCell.h"
#import "WDProvinceList.h"
#import "WDOriImageController.h"
#import "WDProductDynamicController.h"
#import "IQKeyboardManager.h"

@interface WDProductDetailController () <UITableViewDelegate, UITableViewDataSource, WDProductBottomViewDelegate, WDAnimateViewDelegate, WDMaterialCellDelegate>
{
    BOOL _wasKeyboardManagerEnabled;
}

/** tableView */
@property (nonatomic, strong) UITableView *detailTableView;
/** 产品详情数据 */
@property (nonatomic, strong) WDProductDetail *productDetail;
/** cell的数组数据 */
@property (nonatomic, strong) NSMutableArray *cellArray;
/** cell左边数据 */
@property (nonatomic, strong) NSMutableArray *leftArray;
/** cell的高度 */
@property(nonatomic,strong)NSMutableDictionary *dicH;
/** 收藏状态 0:未改变 1:改变 */
@property (assign, nonatomic) BOOL collectChange;
/** 金额 */
@property (nonatomic, strong) NSString *amountMoney;
/** 分期 */
@property (nonatomic, strong) NSString *termStr;
/** 年利化率 */
@property (nonatomic, strong) NSString *interestStr;
/** 占位 */
@property (strong, nonatomic) WDPlaceholderView *placeView;

@end

@implementation WDProductDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //添加这句话，tableView就不会被遮盖
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    if (self.isDynamic) {
        
        NSArray *productNames = [self.productName componentsSeparatedByString:@"-"];
        
        [self loadNavItemWithAction:@selector(clickBackBtn) btnImage:@"icon_back" btnSelImage:@"icon_back" title:[NSString stringWithFormat:@"%@ %@", productNames[0], productNames[1]]];
        
    } else {
        
      [self loadNavItemWithLeftAction:@selector(clickBackBtn) leftBtnImage:@"icon_back" leftBtnSelImage:@"icon_back" title:[NSString stringWithFormat:@"%@ %@", self.product.parent_name, self.product.name] rihgtAction:@selector(clickRightBtn) rightBtnImage:@"icon-operation_his" rightBtnSelImage:@"icon-operation_his"];
        
    }
    
    //关闭抽屉模式
    [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
    
    if (self.productId) {
        //从数据库中查找
        WDSQLiteManager *manager = [WDSQLiteManager manager];
        NSArray *dataArr = [manager selectWithTable:NSStringFromClass([WDProduct class]) whereCondition:@{@"id":self.productId}];
        //WDLog(@"%@", NSHomeDirectory());
        
        if (dataArr.count) {
            self.product = dataArr[0];
        }

    }
    
    [self showLoadView];
    
    //发网络请求，获得数据
    [self sendRequestData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    
    self.navigationController.navigationBar.hidden = NO;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
//    [[IQKeyboardManager sharedManager] setEnable:NO];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

#pragma mark 保存cell高度
- (NSMutableDictionary *)dicH
{
    if(_dicH == nil) {
        _dicH = [[NSMutableDictionary alloc] init];
    }
    return _dicH;
}

#pragma mark - 按钮点击
- (void)clickBackBtn
{
    
    if (self.productID) {
        
        self.productID(self.product.id, self.collectChange);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)clickRightBtn
{
    //跳转产品动态页面
    WDProductDynamicController *tempV = [[WDProductDynamicController alloc] init];
    
    tempV.productID = self.product.id;
    tempV.parentLogo = self.product.parent_logo;
    tempV.productName = [NSString stringWithFormat:@"%@-%@", self.product.parent_name, self.product.name];
    
    tempV.view.backgroundColor = WDBackColor;
    
    [self.navigationController pushViewController:tempV animated:YES];
    
}

#pragma mark - 加载控件
- (void)setUpDetailTableView
{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.sectionFooterHeight = 0;
    
    [self.view addSubview:tableView];
    
    self.detailTableView = tableView;
    
    [tableView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(0);
        make.bottom.equalTo(48);
    }];
    
    tableView.contentInset = UIEdgeInsetsMake(0, 0, 77, 0);
}

- (void)setUpBottomView
{
    WDProductBottomView *bottomView = [WDProductBottomView productBottomView];
    bottomView.delegate = self;
    
    if ([self.product.favorite boolValue]) {//是否收藏
        bottomView.collect = YES;
    } else {
        bottomView.collect = NO;
    }
    
    [self.view addSubview:bottomView];
    
    [bottomView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(0);
        make.height.equalTo(48);
    }];
}

#pragma mark - 记载控件
//加载占位图
- (void)showLoadView
{
    self.placeView = [WDPlaceholderView placeholderViewWithImageName:@"icon_loading" status:@"努力加载中..."];
    [self.view addSubview:self.placeView];
    
    [self.placeView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(100);
        make.left.right.bottom.equalTo(0);
    }];
}

//移除占位图
- (void)hideLoadView
{
    [self.placeView removeFromSuperview];
}

#pragma mark - lazy load
- (NSMutableArray *)leftArray
{
    if (_leftArray == nil) {
        
        NSString *path = [[NSBundle mainBundle] pathForResource:@"WDPDLeftBottom.plist" ofType:nil];
        
        NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
        
        NSDictionary *dict = nil;
        
        NSMutableArray *leftBottomArr = [NSMutableArray array];
        
        for (dict in dictArray) {
            
            WDPDLeftBottom *leftBottom = [WDPDLeftBottom pdLeftBottomWithDict:dict];
            
            [leftBottomArr addObject:leftBottom];
        }
        _leftArray = leftBottomArr;
    }
    return _leftArray;
}

#pragma mark - 发网络请求
- (void)sendRequestData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    if (!self.product) {
        self.product.id = self.productId;
    }
    
    NSDictionary *parameters = @{
                                 @"id":self.product.id,
                                 @"ctype":@3
                                 };
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLProductDetail];
    
    [manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self hideLoadView];
        
        self.productDetail = [WDProductDetail mj_objectWithKeyValues:responseObject];
        
        NSString *borrower_credit;
        NSString *spouse_credit;
        NSString *province_remark;
        NSString *ageRange;
        
        if (self.productDetail.age_start == nil || self.productDetail.age_end == nil) {
            ageRange = @"0周岁";
        } else {
            ageRange = [NSString stringWithFormat:@"%@-%@周岁", self.productDetail.age_start, self.productDetail.age_end];
        }
        
        if ([self.productDetail.borrower_credit boolValue]) {
            borrower_credit = @"需要";
        } else {
            borrower_credit = @"不需要";
        }
        if ([self.productDetail.spouse_credit boolValue]) {
            spouse_credit = @"需要";
        } else {
            spouse_credit = @"不需要";
        }
        if ([self.productDetail.outsettling_province_count integerValue] > 0) {
            province_remark = @"省份非空";
        } else {
            province_remark = @"";
        }
        
        if (self.productDetail.fitness_value == nil) {
            self.productDetail.fitness_value = @"-";
        }
        if (self.productDetail.approve_speed_value == nil) {
            self.productDetail.approve_speed_value = @"-";
        }
        if ([self.productDetail.addition_finance isEqualToString:@""]) {
            self.productDetail.addition_finance = @"-";
        }
        if ([self.productDetail.gps isEqualToString:@""]) {
            self.productDetail.gps = @"-";
        }
        if ([self.productDetail.product_explain isEqualToString:@""]) {
            self.productDetail.product_explain = @"-";
        }
        
        NSMutableArray *dictArray= (NSMutableArray *)@[
                                             @{@"value" : self.productDetail.approve_speed_value,@"remark" : @""},
                                             @{@"value" : self.productDetail.fitness_value,@"remark" : @""},
                                             @{@"value" : ageRange,@"remark" : self.productDetail.age_remark},
                                             @{@"value" : self.productDetail.addition_finance,@"remark" : @""},
                                             @{@"value" : self.productDetail.gps,@"remark" :@""},
                                             @{@"value" : [NSString stringWithFormat:@"%@个省市", self.productDetail.outsettling_province_count],@"remark" : province_remark},
                                             @{@"value" : borrower_credit,@"remark" :self.productDetail.borrower_credit_remark},
                                             @{@"value" : spouse_credit,@"remark" : self.productDetail.spouse_credit_remark},
                                             @{@"value" : @"",@"remark" :@""},
                                             @{@"value" :self.productDetail.product_explain ,@"remark" : @""},
                                             ];
        
        self.cellArray = [WDPDBottom mj_objectArrayWithKeyValuesArray:dictArray];
        
        [self setUpDetailTableView];
        
        //加载底部视图
        if ([WDVerify verifyStr:finance_create inArr:[[NSUserDefaults standardUserDefaults] objectForKey:verStr]]) {
            
            [self setUpBottomView];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //WDLog(@"%@",error);
        
    }];
}

#pragma mark - <tableView代理>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 1;
            break;
            
        case 1:
            return 1;
            break;
            
        case 2:
            return 10;
            break;
            
        default:
            return 0;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            WDPDHeadCell *cell = [WDPDHeadCell pdHeadCellWithTableView:tableView];
            
            cell.product = self.product;
            cell.productDetail = self.productDetail;
            
            return cell;
            
        }
            break;
            
        case 1:
        {
            WDAnimateCell *cell = [WDAnimateCell animateCellWithTableView:tableView];
            cell.delegate = self;
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            cell.product = self.product;
            
            return cell;
        }
            break;
            
        case 2:
        {
            if (indexPath.row == 8) {
                WDMaterialCell *cell = [WDMaterialCell materialCellWithTableView:tableView];
                
                cell.indexPath = indexPath;
                
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                cell.delegate = self;
                
                cell.productDetail = self.productDetail;
                
                cell.leftBottom = self.leftArray[indexPath.row];
                cell.bottom = self.cellArray[indexPath.row];
                
                return cell;
                
            } else if (indexPath.row == 2 || indexPath.row == 5 || indexPath.row == 6 || indexPath.row == 7) {
                WDPDIntroCell *cell = [WDPDIntroCell introCellWithTableView:tableView];
                
                cell.leftBottom = self.leftArray[indexPath.row];
                cell.bottom = self.cellArray[indexPath.row];
                
                return cell;
                
            } else if (indexPath.row == 9) {
                
                WDPDDescCell *cell = [WDPDDescCell descCellWithTableView:tableView];
                
                cell.bottom = self.cellArray[indexPath.row];
                
                return cell;
                
            } else {
                WDPDDefaultCell *cell = [WDPDDefaultCell defaultCellWithTableView:tableView];
                
                cell.leftBottom = self.leftArray[indexPath.row];
                cell.bottom = self.cellArray[indexPath.row];
                return cell;
            }
        }
            break;
            
        default:
            return nil;
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.section) {
        case 0://查看机构详情
        {
            
            WDFinancialDetailController *tempV = [[WDFinancialDetailController alloc] init];
            
            tempV.productDetail = self.productDetail;
            
            tempV.view.backgroundColor = [UIColor whiteColor];
            
            [self.navigationController pushViewController:tempV animated:YES];
        }
            break;
            
        case 2://弹出提示
        {
            switch (indexPath.row) {
                case 2://年龄
                {
                    if (![self.productDetail.age_remark isEqualToString:@""]) {
                        
                        [self showAlertWithMessage:self.productDetail.age_remark];
                    }
                }
                    break;
                    
                case 5://省市
                {
                    if ([self.productDetail.outsettling_province_count integerValue] > 0) {
                        //跳转省份
                        WDCityListController *cityV = [[WDCityListController alloc] init];
                        
                        NSArray *provinces = [WDProvinceList mj_objectArrayWithKeyValuesArray:self.productDetail.province_list];
                        
                        cityV.provinces = provinces;
                        
                        cityV.view.backgroundColor = WDBackColor;
                        [self.navigationController pushViewController:cityV animated:YES];
                    }
                }
                    break;
                    
                case 6://主贷人征信
                {
                    if (![self.productDetail.borrower_credit_remark isEqualToString:@""]) {
                        
                        [self showAlertWithMessage:self.productDetail.borrower_credit_remark];
                    }
                }
                    break;
                    
                case 7://配偶征信
                {
                    if (![self.productDetail.spouse_credit_remark isEqualToString:@""]) {
                        
                        [self showAlertWithMessage:self.productDetail.spouse_credit_remark];
                    }
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;
            
        default:
            break;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        UIView *tempV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WDScreenW, 12)];
        
        tempV.backgroundColor = [UIColor whiteColor];

        return tempV;
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        return 12;
    } else {
        return 16;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            return self.productDetail.cellH;
            
        }
            break;
            
        case 1:
        {
            return 290;
        }
            break;
            
        case 2:
        {
            WDPDBottom *pdBottom = self.cellArray[indexPath.row];
            return pdBottom.cellHeight;
        }
            break;
            
        default:
            return 0;
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}

#pragma mark - <WDProductBottomViewDelegate>
//点击收藏/取消收藏
- (void)productBottomViewCollectWithButton:(UIButton *)btn
{
    self.collectChange = !self.collectChange;
    
    if (!btn.isSelected) {//收藏
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
        if([cookiesdata length]) {
            NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
            NSHTTPCookie *cookie;
            for (cookie in cookies) {
                [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
            }
        }
        
        NSDictionary *parameters = @{
                                     @"product_id":self.product.id,
                                     @"ctype":@3
                                     
                                     };
        NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLProductCollect];
        
        //加蒙版
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD show];
        
        [manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //更新这条数据
            WDSQLiteManager *manager = [WDSQLiteManager manager];
            
            NSDictionary *keyValues = @{
                                        @"favorite":@1
                                        };
            
            NSDictionary *condition = @{
                                        @"id":self.product.id
                                        };
            
            [manager updateWithTable:NSStringFromClass([WDProduct class]) setKeyValues:keyValues whereCondition:condition];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                //改变按钮
                btn.selected = !btn.selected;
                
                if (btn.isSelected) {
                    btn.backgroundColor = ColorForRGB(0xc7c7c7);
                } else {
                    btn.backgroundColor = ColorForRGB(0xf1a636);
                    
                }
                [WDPromptBox showPromptBoxWithMassage:@"收藏成功"];
                [SVProgressHUD dismiss];
            });
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [WDPromptBox showPromptBoxWithMassage:@"收藏失败"];
            
        }];
        
    } else {//取消收藏
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
        if([cookiesdata length]) {
            NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
            NSHTTPCookie *cookie;
            for (cookie in cookies) {
                [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
            }
        }
        
        NSDictionary *parameters = @{
                                     @"product_id":self.product.id,
                                     @"ctype":@3
                                     };
        NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLProductCancelCollect];
        
        //加蒙版
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD show];
        
        [manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            //更新这条数据
            WDSQLiteManager *manager = [WDSQLiteManager manager];
            
            NSDictionary *keyValues = @{
                                        @"favorite":@0
                                        };
            
            NSDictionary *condition = @{
                                        @"id":self.product.id
                                        };
            
            [manager updateWithTable:NSStringFromClass([WDProduct class]) setKeyValues:keyValues whereCondition:condition];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                btn.selected = !btn.selected;
                
                if (btn.isSelected) {
                    btn.backgroundColor = ColorForRGB(0xc7c7c7);
                } else {
                    btn.backgroundColor = ColorForRGB(0xf1a636);
                }
                [WDPromptBox showPromptBoxWithMassage:@"取消收藏"];
                [SVProgressHUD dismiss];
            });;
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [SVProgressHUD dismiss];
            
            [WDPromptBox showPromptBoxWithMassage:@"取消收藏失败"];
            
        }];
        
    }
}

//点击申请贷款
- (void)productBottomViewApplyLoanWithButton:(UIButton *)btn
{
    //跳转新建贷款页
    WDEditOrderController *tempV = [[UIStoryboard storyboardWithName:@"WDEditOrderController" bundle:nil] instantiateViewControllerWithIdentifier:@"WDEditOrderController"];
    
    //传参数
    self.product.financeamount_current = self.amountMoney;
    self.product.term_current = self.termStr;
    self.product.interest_current = self.interestStr;
    
    tempV.product = self.product;
    
    tempV.applyLoan = YES;
    
    
    tempV.view.backgroundColor = WDBackColor;
    
    [self.navigationController pushViewController:tempV animated:YES];
}

#pragma mark - <WDAnimateDelegate>
- (void)showErrorAlert:(UITextField *)textFiled value:(NSString *)value
{
    [self showAlertWithMessage:@"请输入正确的金额范围"];
    textFiled.text = [NSString stringWithFormat:@"%.1f", [value floatValue]];
}

- (void)chooseResult:(NSString *)amountMoney term:(NSString *)term interest:(NSString *)interest
{
    self.amountMoney = amountMoney;
    self.termStr = term;
    self.interestStr = interest;
}

#pragma mark - <WDMaterialCellDelegate>
//跳转到大图浏览
- (void)materialCell:(WDMaterialCell *)materialCell ShowOriginalImages:(NSArray *)originalImages index:(NSInteger)index
{
    WDOriImageController *tempV = [[WDOriImageController alloc] init];
    tempV.images = originalImages;
    tempV.index = index;
    tempV.view.backgroundColor = WDBackColor;
    
    [self.navigationController pushViewController:tempV animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
